#include "stdafx.h"
#include "FMODsound.h"

bool Sound::sEnabled = true; //Is the sound Enabled?
char *Sound::sCurrentSound; //current sound to play
//FMOD system stuff

FMOD_RESULT Sound::sResult;
FMOD_SYSTEM *Sound::sFmodSystem;
FMOD_SOUND *Sound::sSound;
FMOD_CHANNEL *Sound::sChannel;
void Sound::Init()
{
    sResult = FMOD_System_Create(&sFmodSystem);
assert(sResult == FMOD_OK);
//Initializes the system with 1 channel
sResult = FMOD_System_Init(sFmodSystem,1, FMOD_INIT_NORMAL, 0);
assert(sResult == FMOD_OK);
FMOD_Channel_SetVolume(sChannel,0.0f);
}
void Sound::Update()
{
FMOD_System_Update(sFmodSystem);
}


void Sound::SetVolume (float vol) 
{
    if (sEnabled && vol >= 0.0f && vol <= 1.0f) 
{
        FMOD_Channel_SetVolume(sChannel,vol);
    }
}


//loads a soundfile
void Sound::Load (const char * filename) 
{
    sCurrentSound = (char *)filename;
    if (sEnabled) 
{
        sResult = FMOD_Sound_Release(sSound);
        sResult = FMOD_System_CreateStream(sFmodSystem,sCurrentSound, FMOD_SOFTWARE, 0, &sSound);
assert(sResult == FMOD_OK);
    }
}




void Sound::Unload (void) 
{
sResult = FMOD_Sound_Release(sSound);
assert(sResult == FMOD_OK);
}




void Sound::Play (bool pause = false) //No agument is needed to play by default
{
    if (true == sEnabled) 
	{
        sResult = FMOD_System_PlaySound(sFmodSystem,FMOD_CHANNEL_FREE, sSound, pause, &sChannel);
		assert(sResult == FMOD_OK);
		FMOD_Channel_SetMode(sChannel,FMOD_LOOP_NORMAL); //FMOD_LOOP_OFF
    }
}


bool Sound::GetSoundState () 
{
    return sEnabled;
}
//Gets the name of the current sound
char* Sound::GetCurrentSound()
{
return sCurrentSound;
}




//pause or unpause the sound
void Sound::SetPause (bool pause) 
{
FMOD_Channel_SetPaused (sChannel, pause);
}


//turn sound on or off
void Sound::SetSound (bool s) 
{
    sEnabled = s;
}


//toggles sound on and off
void Sound::ToggleSound (void) 
{
    sEnabled = !sEnabled;
    if (sEnabled == true) 
{ 
Load(sCurrentSound); 
Play(sEnabled); 
}
    if (sEnabled == false) 
{ 
Unload(); 
}
}


//toggle pause on and off
void Sound::TogglePause (void) 
{
    FMOD_BOOL p;
    FMOD_Channel_GetPaused(sChannel,&p);
    FMOD_Channel_SetPaused(sChannel,!p);
}

//Gets the sound system
FMOD_SYSTEM* Sound::GetSystem()
{
return sFmodSystem;
}

 //-------------Sound Effects---------------//
SoundEffect::SoundEffect(char* filename)
{
	bEnabled = true;
	mSoundName = filename;
	mResult = FMOD_System_CreateSound(Sound::GetSystem(),mSoundName, FMOD_SOFTWARE, 0, &mSound);
	assert(mResult == FMOD_OK);
}

void SoundEffect::Play()
{
	mResult = FMOD_System_PlaySound(Sound::GetSystem(),FMOD_CHANNEL_FREE, mSound, false, 0);
	assert(mResult == FMOD_OK);
}